package com.sun.aviator.fun;

import cn.hutool.json.JSONUtil;
import com.googlecode.aviator.runtime.function.AbstractFunction;
import com.googlecode.aviator.runtime.function.FunctionUtils;
import com.googlecode.aviator.runtime.type.*;

import java.math.BigDecimal;
import java.math.MathContext;
import java.util.Map;

/**
 * @Author: Suncl
 * @Date: 2023/10/27 17:16
 */
public class DivideFuntion extends AbstractFunction {
    @Override
    public AviatorObject call(Map<String, Object> env,AviatorObject arg1, AviatorObject arg2) {
        System.out.println("进入DivideFuntion类 开始计算");
        System.out.println("env参数 = " + JSONUtil.toJsonStr(env));
        BigDecimal a = getDecimal(env, arg1);
        BigDecimal b = getDecimal(env, arg2);
        String valueOf = a.divide(b,new MathContext(3)).toString();
        return new AviatorString(valueOf);
    }

    @Override
    public String getName() {
        return "divide";
    }

    private BigDecimal getDecimal(Map<String, Object> env,AviatorObject arg){
        BigDecimal decimal;
        MathContext mathContext = new MathContext(3);
        if (arg == null){
            decimal = new BigDecimal("0",mathContext);
        }else {
            if (arg instanceof AviatorString){
                decimal = new BigDecimal(FunctionUtils.getStringValue(arg,env),mathContext);
            }else if (arg instanceof AviatorLong) {
                decimal = new BigDecimal(String.valueOf(arg.getValue(env)),mathContext);
            }else {
                Object value = arg.getValue(env);
                decimal = (BigDecimal) value;
            }


        }
        return decimal;
    }
}
